package com.tianji.aigc.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.tianji.aigc.agent.AbstractAgent;
import com.tianji.aigc.agent.Agent;
import com.tianji.aigc.enums.AgentTypeEnum;
import com.tianji.aigc.enums.ChatEventTypeEnum;
import com.tianji.aigc.service.ChatService;
import com.tianji.aigc.vo.ChatEventVO;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.Objects;

@Service
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "tj.ai", name = "chat-type", havingValue = "ROUTE")
public class AgentServiceImpl implements ChatService {
    @Override
    public Flux<ChatEventVO> chat(String question, String sessionId) {

        // 先把问题，发给意图分析智能体，再决定由哪个智能体来执行
        var result = Objects.requireNonNull(this.findAgentByType(AgentTypeEnum.ROUTE)).process(question, sessionId);

        // 通过结果，尝试查找智能体实例，如果能找到，就进行执行，找不到，就说明路由智能体可以处理的问题，直接返回即可
        Agent agent = this.findAgentByType(AgentTypeEnum.agentNameOf(result));
        if (agent == null) {
            ChatEventVO chatEventVO = ChatEventVO.builder()
                    .eventType(ChatEventTypeEnum.DATA.getValue())
                    .eventData(result)
                    .build();
            return Flux.just(chatEventVO, AbstractAgent.STOP_EVENT);
        }

        // 交由下游的智能体处理
        return agent.processStream(question, sessionId);
    }

    private Agent findAgentByType(AgentTypeEnum agentTypeEnum) {
        if (null == agentTypeEnum) {
            return null;
        }

        return SpringUtil.getBeansOfType(Agent.class).values().stream()
                .filter(agent -> agent.getAgentType() == agentTypeEnum)
                .findFirst()
                .orElse(null);
    }

    @Override
    public void stop(String sessionId) {

    }

    @Override
    public String chatText(String question) {
        return "";
    }
}
